package com.ita.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sound.midi.VoiceStatus;

import org.apache.activemq.filter.function.inListFunction;
import org.apache.catalina.Session;
import org.aspectj.weaver.reflect.ReflectionBasedResolvedMemberImpl;
import org.hibernate.persister.collection.ElementPropertyMapping;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ita.annotation.ControllerLog;
import com.ita.pojo.Food;
import com.ita.pojo.FoodType;
import com.ita.pojo.MUser;
import com.ita.service.FoodService;
import com.ita.service.MUserService;
import com.ita.util.Constant;
import com.ita.util.FileUtil;
import com.ita.vo.FoodVo;
import com.ita.vo.JsonResult;

@Controller(value = "foodController")
@RequestMapping("/sec/food")
@RestController
public class FoodController {

	@Resource(name = "foodService")
	private FoodService fService;

	@Resource(name = "muserService")
	private MUserService mService;

	@RequestMapping(value = "add", method = RequestMethod.POST)
	// @ResponseBody
	public JsonResult add(MultipartHttpServletRequest req, HttpSession session) throws IOException {
		String server_path = null;
		JsonResult jr = new JsonResult();

		try {
			server_path = "http://" + InetAddress.getLocalHost().getHostAddress() + Constant.FILE_PORT;
		} catch (UnknownHostException e) {
			jr.setCode(Constant.EXCEPTION);
			jr.setMsg("Image server exception");
			return jr;
		}

		// "name":name,"price":price,"type":type
		String m_id = ((MUser) session.getAttribute(Constant.CURRENT_MERCHANT)).getId();
		String name = req.getParameter("name");
		String price = req.getParameter("price");
		String type = req.getParameter("type");

		if (("".equals(name)) || ("".equals(price)) || ("".equals(type))) {
			jr.setMsg("Fields are empty !");
			jr.setCode(Constant.FAIL);
			return jr;
		}

		Food food = new Food();

		food.setId(UUID.randomUUID().toString());

		MUser merchant = mService.getById(m_id);
		food.setMerchant(merchant);

		FoodType foodType = fService.loadFoodType(type);
		food.setType(foodType);

		food.setName(name);

		food.setPrice(Double.parseDouble(price));

		// food.setPrice(123);

		String img = Constant.FOOD;
		String filePath = "";

		Iterator<String> iter = req.getFileNames();
		while (iter.hasNext()) {

			MultipartFile file = req.getFile(iter.next());
			if (file != null) {

				String fileName = file.getOriginalFilename();
				String image_type = fileName.subSequence(fileName.lastIndexOf("."), fileName.length()).toString();
				if (".jpg".equals(image_type) || ".gif".equals(image_type) || ".jpeg".equals(image_type)
						|| ".png".equals(image_type)) {
					InputStream in = file.getInputStream();
					byte[] buff = new byte[in.available()];
					in.read(buff);
					filePath = Constant.FOOD_PATH + food.getId() + image_type;
					img = img + food.getId() + image_type;
					FileUtil.writeFile(filePath, buff);
					in.close();
				} else {
					jr.setCode(Constant.FAIL);
					jr.setMsg("Image format error");
					return jr;
				}
			} else {
				jr.setCode(Constant.FAIL);
				jr.setMsg("Not select image");
				return jr;
			}
		}

		food.setImg(server_path + img);

		try{
			Food tmp = fService.addFood(food);
			jr.setCode(Constant.SUCCESS);
			jr.setData(po2vo(tmp));
		}catch (Exception e) {
			jr.setCode(Constant.FAIL);
			return jr;
		}
		
		return jr;

	}

	@RequestMapping(value = "del", method = RequestMethod.DELETE)
	// @ResponseBody
	@ControllerLog(description = "des food")
	public JsonResult delete(String id) {
		// System.out.println("del " + id);
		JsonResult jr = new JsonResult();
		Food tmp = null;
		try {
			tmp = fService.deleteFood(id);
			jr.setCode(Constant.SUCCESS);
			jr.setData(po2vo(tmp));
		} catch (Exception e) {
			jr.setCode(Constant.FAIL);
			return jr;
		}

		return jr;
	}

	@RequestMapping(value = "fmodify", method = RequestMethod.POST)
	// @ResponseBody
	@ControllerLog(description = "modify the food content")
	public JsonResult fmodify(MultipartHttpServletRequest req, HttpSession session) throws IOException {
		String server_path = null;
		JsonResult jr = new JsonResult();

		try {
			server_path = "http://" + InetAddress.getLocalHost().getHostAddress() + Constant.FILE_PORT;
		} catch (UnknownHostException e) {
			jr.setCode(Constant.EXCEPTION);
			jr.setMsg("Image server exception");
			return jr;
		}

		// "name":name,"price":price,"type":type
		String m_id = ((MUser) session.getAttribute(Constant.CURRENT_MERCHANT)).getId();
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String price = req.getParameter("price");
		String type = req.getParameter("type");

		if (("".equals(name)) || ("".equals(price)) || ("".equals(type))) {
			jr.setMsg("Fields are empty !");
			jr.setCode(Constant.FAIL);
			return jr;
		}

		Food food = new Food();

		food.setId(id);

		MUser merchant = mService.getById(m_id);
		food.setMerchant(merchant);

		FoodType foodType = fService.loadFoodType(type);
		food.setType(foodType);

		food.setName(name);

		food.setPrice(Double.parseDouble(price));

		// food.setPrice(123);

		String img = Constant.FOOD;
		String filePath = "";

		Iterator<String> iter = req.getFileNames();
		while (iter.hasNext()) {

			MultipartFile file = req.getFile(iter.next());
			if (file != null) {

				String fileName = file.getOriginalFilename();
				String image_type = fileName.subSequence(fileName.lastIndexOf("."), fileName.length()).toString();
				if (".jpg".equals(image_type) || ".gif".equals(image_type) || ".jpeg".equals(image_type)
						|| ".png".equals(image_type)) {
					InputStream in = file.getInputStream();
					byte[] buff = new byte[in.available()];
					in.read(buff);
					filePath = Constant.FOOD_PATH + food.getId() + image_type;
					img = img + food.getId() + image_type;
					FileUtil.writeFile(filePath, buff);
					in.close();
				} else {
					jr.setCode(Constant.FAIL);
					jr.setMsg("Image format error");
					return jr;
				}
			} else {
				jr.setCode(Constant.FAIL);
				jr.setMsg("Not select image");
				return jr;
			}
		}

		food.setImg(server_path + img);

		try{
			fService.updateFood(food);
			jr.setCode(Constant.SUCCESS);
			jr.setData(po2vo(food));
		}catch (Exception e) {
			jr.setCode(Constant.FAIL);
			return jr;
		}
		
		return jr;

	}

	// @RequestMapping(value = "fmodify", method = RequestMethod.POST, consumes
	// = "application/json")
	// @ResponseBody
	// public Food modify(@RequestBody Food food) {
	// return fService.updateFood(food);
	// }

	@RequestMapping(value = "list", method = RequestMethod.GET)
	// @ResponseBody
	public JsonResult findAllFood(HttpSession session) {
		JsonResult jr = new JsonResult();
		String m_id = ((MUser) session.getAttribute(Constant.CURRENT_MERCHANT)).getId();

		try {
			List<Food> foods = fService.findAll(m_id);
			List<FoodVo> foodVos = new ArrayList<>();

			for (Food food : foods) {
				foodVos.add(po2vo(food));
			}
			jr.setCode(Constant.SUCCESS);
			jr.setData(foodVos);
		} catch (Exception e) {
			jr.setCode(Constant.FAIL);
			return jr;
		}

		return jr;
	}

	@RequestMapping(value = "type", method = RequestMethod.GET)
	// @ResponseBody
	@ControllerLog(description = "get food type")
	public List<FoodType> findAllType() {
		List<FoodType> foodTypes = fService.loadFoodType();
		return foodTypes;
	}

	@RequestMapping(value = "goup", method = RequestMethod.POST, consumes = "application/json")
	// @ResponseBody
	@ControllerLog(description = "get food content")
	public JsonResult get(String id) {
		System.out.println("get " + id);

		JsonResult jr = new JsonResult();
		try {
			Food food = fService.loadFoodById(id);
			jr.setCode(Constant.SUCCESS);
			jr.setData(po2vo(food));
		} catch (Exception e) {
			jr.setCode(Constant.FAIL);
			return jr;
		}

		return jr;

	}

	private FoodVo po2vo(Food food) throws Exception{

		if (food == null) {
			return null;
		}
		FoodVo vo = new FoodVo();
		vo.setId(food.getId());
		vo.setImg(food.getImg());
		vo.setName(food.getName());
		vo.setPrice(food.getPrice());
		vo.setTypeName(food.getType().getName());
		return vo;
	}

}
